﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Extensions;

namespace ERPStore.NewsLetters.Services
{
	public class AllContactRecipientSourceProvider : IEmailListSourceProvider
	{
		private ERPStore.Models.UserListFilter m_Filter;

		public AllContactRecipientSourceProvider(ERPStore.Services.IAccountService accountService
			, ERPStore.Services.IValidatorService validator
			, NewsLettersService newsLetterService
			, ERPStore.Logging.ILogger logger)
		{
			this.AccountService = accountService;
			this.ValidatorService = validator;
			this.NewsLetterService = newsLetterService;
			this.Logger = logger;
		}

		protected ERPStore.Services.IAccountService AccountService { get; private set; }
		protected ERPStore.Services.IValidatorService ValidatorService { get; private set; }
		protected NewsLettersService NewsLetterService { get; private set; }
		protected ERPStore.Logging.ILogger Logger { get; private set; }

		#region IRecipientListProvider Members

		public void Initialize(Models.EmailListSource source)
		{
			if (source == null)
			{
				throw new ArgumentException("source does not be null");
			}
			m_Filter = new ERPStore.Models.UserListFilter();
			m_Filter.HasEmail = true;
		}

		public IEnumerable<Models.EmailRecipient> GetList(int pageIndex, int pageSize, out int count)
		{
			count = 0;
			if (m_Filter == null)
			{
				return null;
			}
			var result = new List<Models.EmailRecipient>();
			var list = AccountService.GetUserListByFilter(m_Filter, pageIndex, pageSize, out count);
			Logger.Info("Loading user list {0} / {1}", (pageIndex + 1) * pageSize , count);
			foreach (var item in list)
			{
				if (item.Email.IsNullOrTrimmedEmpty())
				{
					continue;
				}
				var rcp = NewsLetterService.GetEmailRecipientByEmail(item.Email.Trim());
				if (rcp == null)
				{
					rcp = AutoMapper.Mapper.Map<Models.EmailRecipient>(item);
				}
				else
				{
					bool bl = rcp.IsBlackListed;
					rcp = AutoMapper.Mapper.Map<ERPStore.Models.User, Models.EmailRecipient>(item, rcp);
					rcp.IsBlackListed = bl;
				}
				try
				{
					NewsLetterService.SaveEmailRecipient(rcp);
				}
				catch (Exception ex)
				{
					Logger.Error(ex);
					continue;
				}
				if (!rcp.IsBlackListed)
				{
					result.Add(rcp);
				}
			}

			return result;
		}

		public string SourceTypeId
		{
			get { return "00648954-D8A2-4EA6-988E-1614A103B2F88"; }
		}

		public string DisplayName
		{
			get
			{
				return "Tous les contacts";
			}
		}

		public IList<ERPStore.Models.BrokenRule> Validate()
		{
			return new List<ERPStore.Models.BrokenRule>();
		}

		public string GetSerializedSettings()
		{
			return m_Filter.SerializeToXml();
		}
		#endregion

	}
}
